package com.qingzhuge.common.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.ContextStoppedEvent;

import javax.validation.constraints.NotNull;

/**
 * @author : zero.xiao
 * @description : 应用状态监听器
 * @modified :
 */
@Slf4j
public abstract class BaseReadyListener implements ApplicationListener {

    @Override
    public void onApplicationEvent(@NotNull ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            // 初始化环境变量
            log.debug("Application Initialize the environment variable");
        } else if (event instanceof ApplicationPreparedEvent) {
            // 初始化完成
            log.debug("Application Initialization is complete");
        } else if (event instanceof ContextRefreshedEvent) {
            // 应用刷新
            log.debug("Application refresh");
        } else if (event instanceof ApplicationReadyEvent) {
            // 应用已启动完成
            String server = ((ApplicationReadyEvent) event)
                    .getSpringApplication()
                    .getAllSources()
                    .iterator()
                    .next()
                    .toString();
            log.info("Application [{}] starting", server.substring(server.lastIndexOf(".") + 1));
        } else if (event instanceof ContextStartedEvent) {
            // 应用启动，需要在代码动态添加监听器才可捕获
            log.debug("Application startup");
        } else if (event instanceof ContextStoppedEvent) {
            // 应用停止
            log.debug("Application stop");
        } else if (event instanceof ContextClosedEvent) {
            // 应用关闭
            log.debug("Application closed");
        }
    }
}
